import React, { useEffect, useState, useRef, useLayoutEffect } from 'react';
import Cursor from '../Cursor';
import { useSnapshot } from 'valtio';
import messageEvent from '../../proxy/messageEvent';
const currentLocation = window.location;
const url = 'ws://' + currentLocation.hostname + ':' + 3005;
const ws = new WebSocket(url)

const Socket: React.FC = () => {
  const newMessageEvent = useSnapshot(messageEvent);
  const container = useRef()
  const [message, setMessage] = useState(['欢迎使用全新一代打包机']);
  useEffect(() => {
    ws.onmessage = e => {
      if (e.data === "打包完成") {
        messageEvent.canOperation = true
      }
      message.push(e.data)
      setMessage([...message])
    };
  }, [container.current]);
  useEffect(() => {
    if (!container.current) return
    container.current.scrollTop = container.current.scrollHeight;
  }, [message]);
  useLayoutEffect(() => {
    if (ws) {
      return () => {
        ws.current?.close();
      }
    }
  }, [ws])
  const renderLi = message.map((item, i) => (
    <li key={item + '_' + i}>{item}</li>
  ))
  return (
    <div className="scoket">
      <div style={{ marginTop: 20, marginLeft: -10, }} >
        <span style={{ color: '#71e4df', fontSize: 30, }} >{newMessageEvent.branche}项目</span>
      </div >
      <div
        ref={container}
        style={{
          fontSize: 12,
          marginLeft: -10,
          overflowY: 'hidden',
          width: 600,
          height: 320,
          color: 'orange'
        }}>
        <ul>
          {renderLi}
          <li style={{ color: 'white' }}><Cursor /></li>
        </ul>

      </div>
    </div>
  );
};

export default Socket;
